from flask import redirect, url_for, session, request
from werkzeug.security import generate_password_hash, check_password_hash
from core.blueprints import api_blueprint
from core.blueprints.auth.models import  User
from core.blueprints.auth.new_user import new_user
from core.lib.response import  Response, ResponsePostOne


@api_blueprint.route('/register', methods=['POST'])
def register():
    def cb(json):
        user = User.query.filter_by(username=json['username']).first()
        if not user:
            user=User(username=json['username'], password=generate_password_hash(json['password']))
            new_user(user)
            return Response("注册成功")
        return Response("已存在用户")

    return ResponsePostOne(['username', 'password'],cb)

@api_blueprint.route('/login', methods=['POST'])
def login():
    def cb(json):
        user = User.query.filter_by(username=json['username']).first()
        if user is None:
            return Response('用户不存在')
        if check_password_hash(user.password, json['password']):
            session['uid'] = user.id
            session['username'] = user.username
            # TODO url
            return redirect(url_for('personal.view'))
        return Response('用户名与密码不匹配')

    return ResponsePostOne(['username', 'password'],cb)

@api_blueprint.route('/username', methods=['GET'])
def username():
    return Response({'username': session['username']})

@api_blueprint.route('/uid', methods=['GET'])
def uid():
    return Response({'uid': session['uid']})


